<template>
  <home-header @reset-view="resetView" />
  <!-- 遮罩层 -->
  <main>
    <div class="cover" ref="cover" v-if="coverShow">
      <el-icon size="30px" color="#fff" @click="closeZoom"><CloseBold /></el-icon>
    </div>
    
    <!-- 日志查看器组件 -->
    <LogViewer :visible="showLogViewer" @close="showLogViewer = false" />
    
    <el-row>
      <!-- 左侧 -->
        <!-- 左侧 -->
        <el-col :span="7" class="left">
        <!-- 饼图-->
        <div class="system_info">
          <h3> {{  $t("message.system_info") }}</h3>
          <div class="info_container">
            <aside class="info_item">
              <div class="left">
                <p style="color:#3b71bf;"><span>{{ module_num }}</span>{{ $t("message.num") }}</p>
                <p> {{ $t("message.access_device")}}</p>
              </div>
              <div class="right">
                <img src="http://argus.megasensing.cn:5000/deviceNum.png" />
              </div>
            </aside>

            <aside class="info_item">
              <div class="left">
                <p style="color:#64bbb7;"><span>{{ admin_store.AableSendMsgNum }}</span>{{ $t("message.num") }}</p>
                <p>{{ $t("message.openSms") }}</p>
              </div>
              <div class="right">
                <img src="http://argus.megasensing.cn:5000/user.png" />
              </div>
            </aside>
            <aside class="info_item">
              <div class="left">
                <p style="color:#d498e2;"><span>{{ store.deviceList.length }}</span> {{ $t("message.num") }}</p>
                <p>{{ $t("message.monitoring") }}</p>
              </div>
              <div class="right">
                <img src="http://argus.megasensing.cn:5000/errorNum.png" />
              </div>
            </aside>
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
        <div class="my_chart">
          <div class="chart">
            <h3>
              {{ $t("message.point") }}<span>{{ device_currentId}}</span>{{ $t("message.uv") }}{{ $t("message.lineChart") }}
              <el-icon size="22px" @click="zoom(1)"><FullScreen /></el-icon>
            </h3>
            <div class="chart-item" ref="uvcRef"></div>
            <span class="border_bg_leftTop"></span>
          </div>
          <div class="chart">
            <h3>
              {{ $t("message.point") }}<span>{{ device_currentId }}</span>{{ $t("message.inf") }}{{ $t("message.lineChart") }}
               <el-icon size="22px" @click="zoom(2)"><FullScreen /></el-icon></h3>
            <div class="chart-item" ref="infRef"></div>
            <span class="border_bg_leftTop"></span>
          </div>
        </div>
      </el-col>
      <!-- 中间 -->
      <el-col :span="10">
        <main class="mainCenter">
          <!--标题-->
          <header class="middle-header">
            <!--首页标题-->
            <div class="title">
              {{ $t("message.title") }}
            </div>
            <!--首页描述信息-->
            <div class="description">
              {{ $t("message.desc") }}
            </div>
          </header>
          <!-- 选择模块 -->
          <main class="drawer-main">
            <el-carousel
                v-if="module_list.length > 3"
                indicator-position="none"
                :autoplay="false"
            >
              <el-carousel-item class="grid_layout" v-for="item in Math.ceil(module_list.length/3)" :key="item">
                <div class="module_item" v-for="e in module_list.slice((item-1)*3,item*3)" :key="e.id" @click="taggleDevice(e.id)">
                    <div class="module_bg_img">
                      <div class="img">
                        <img src="../assets/module.active.png" v-if="e.isChecked" />
                        <img src="../assets/module.png" v-else />
                        <p style="margin-top: 10px;color:#e5dc3d;" v-if="e.isChecked">{{ $t("message.point") +' ' + e.id }}</p>
                        <p style="margin-top: 10px;" v-else>{{ $t("message.point") + ' ' +e.id}}</p>
                      </div>
                    </div>
                </div>
              </el-carousel-item>
            </el-carousel>
            <div class="flex_layout" v-else>
              <div class="module_item" v-for="e in module_list" :key="e.id" @click="taggleDevice(e.id)">
                    <div class="img">
                      <img src="../assets/module.active.png" v-if="e.isChecked" />
                      <img src="../assets/module.png" v-else />
                      <p style="margin-top: 10px;color:#e5dc3d;" v-if="e.isChecked">{{ e.deviceName }}</p>
                      <p style="margin-top: 10px;" v-else>{{ e.deviceName }}</p>
                    </div>
                </div>
            </div>
          </main>
          <!-- 历史曲线统计 -->
          <section class="total">
              <!-- 产品分布 -->
              <aside ref="history_pie"></aside>
              <!--  -->
              <aside ref="history_bar"></aside>
          </section>
        </main>
      </el-col>
      <!-- 右侧 -->
      <el-col :span="7" class="right">
        <div class="chart">
          <h3>
            {{ $t("message.point") }}<span>{{ device_currentId}}</span>{{ $t("message.tem") }}{{ $t("message.lineChart") }}
            <el-icon size="22px" @click="zoom(3)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="temRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
        <!-- 饼图 -->
        <div class="chart">
          <h3>{{ $t("message.point") }}<span>{{ device_currentId}}</span>{{ $t("message.hum") }}{{ $t("message.lineChart") }}
            <el-icon size="22px" @click="zoom(4)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="humRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
        <div class="chart">
          <h3>
            {{ $t("message.point") }}<span>{{ device_currentId}}</span>{{ $t("message.pre") }}{{ $t("message.lineChart") }}
             <el-icon size="22px" @click="zoom(5)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="preRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
      </el-col>
    </el-row>
  </main>
</template>
<script lang="ts" setup>
import { onUnmounted } from 'vue'
import {userStore} from "../store/user";
import { moduleStore } from "../store/module"
import { adminStore } from '../store/admin'
import {storeToRefs} from 'pinia'

import { useLogStore } from '../store/log'
import LogViewer from '../components/LogViewer.vue'

type obj = {
   orderName: string,
   id: number,
   refName: string
}
  let store = userStore()
  let admin_store = adminStore()
  let module_store = moduleStore()
  let logStore = useLogStore() // 导入日志存储
  
  // 日志查看器控制
  const showLogViewer = ref(false)
  
  // 监听 Ctrl+H 快捷键
  onMounted(() => {
    window.addEventListener('keydown', handleKeyDown)

    // systemApp.onLogUpdate((data) => {
    //   console.log(data)
    // })
  })
  
  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeyDown)
  })
  
  // 处理快捷键
  const handleKeyDown = (event: KeyboardEvent) => {
    // 检测 Ctrl+H 组合键
    if (event.ctrlKey && event.key === 'h') {
      event.preventDefault() // 阻止默认行为
      showLogViewer.value = !showLogViewer.value // 切换日志查看器显示状态
      
      // 如果打开日志查看器，请求最新日志
      if (showLogViewer.value) {
        window.systemApp.requestLogs()
      }
    }
  }
  
  let params = reactive({
      uv: 7,
      inf: 7,
      other: 7 // 这个参数是调整温度湿度压力的 具体参照 rateLevel数组
    })
  // 速率等级
  let rateLevel = ref<number[]>(
    [10000,7000,5000,3000,2000,1000,700,500,300,100]
  )
  // 初始化监测的手机列表
  admin_store.initPhoneList()
  let { localWebsocket, isLogin, indexDbNum } = storeToRefs(store)
  import {IhttpReturn} from '../until/interface'
  let {device_currentId,module_list,module_num,alarm_type,isShowTip,isOpenVoice,systemInfo,deviceStatusList} = storeToRefs(module_store)
  import HomeHeader from "../components/common/Header.vue"
  import Tool from '../until/tool'
  import * as echarts from "echarts"
  import { ECharts } from "echarts"
  import {setOption} from '../until/chart'
  import {ref,onMounted,reactive,getCurrentInstance, ComponentInternalInstance} from 'vue'
  // 延迟函数
  const delay = (ms:string | number) => new Promise(resolve => setTimeout(resolve,ms))
  let {proxy} = getCurrentInstance() as ComponentInternalInstance
  let resizeObserver: ResizeObserver | null = null
  const chartDomMap = new Map<HTMLElement, ECharts>()
  let resizeTimer:any
  let winResizeHandler:(() => void) | null = null

  // 关于紫外的
  let uvcRef= ref()
  let uvcPirture = reactive<ECharts>({} as ECharts) // 紫外折线图对象
  let uvcArr = reactive<Array<number>>([])
  let uvcMax = ref<number>()
  let uvcMin = ref<number>()

  // 关于红外的
  let infRef = ref()
  let infPirture = reactive<ECharts>({} as ECharts) // 红外折线图对象
  let infArr = reactive<Array<number>>([])
  let infMax = ref<number>()
  let infMin = ref<number>()

  // 关于温度
  let temRef = ref()
  let temPirture = reactive<ECharts>({} as ECharts)  // 温度折线图对象
  let temArr = reactive<Array<number>>([])
  let temMax = ref<number>()
  let temMin = ref<number>()

  // 关于湿度
  let humRef = ref()
  let humArr = reactive<Array<number>>([])
  let humPirture = reactive<ECharts>({} as ECharts) // 湿度折线图对象
  let humMax = ref<number>()
  let humMin = ref<number>()


  // 关于压力
  let preRef = ref()
  let prePirture = reactive<ECharts>({} as ECharts) // 电压折线图对象
  let preArr = reactive<Array<number>>([])
  let preMax = ref<number>()
  let preMin = ref<number>()

  // 关于折线图x轴
  let xaxisData = reactive<number[]>([])
  let time = ref(0)
  let deviceNameList = ref(['message.uv','message.inf','message.tem','message.hum','message.pre'])

  /**放大和缩小展示 */
  let cover = ref() // 放大全屏遮罩层
  let coverShow = ref<boolean>(false)
  let zoomId = ref<number>(0); // 放大id

  // 导入线程模块
  // @ts-ignore
    import sendMsgWorker from '@/worker/sendMsg?worker' // 发送短信的线程
    let sendWorker = new sendMsgWorker() // 发送短信

    // @ts-ignore
    import deleteDataWorker from '@/worker/delData?worker' // 删除数据线程，只存入一周的数据
    let deleteWorker = new deleteDataWorker() // 删除数据

    // 获取模块的个数
    const getModuleNum = async () => {
      if (!module_num.value) {
        // 发送请求获取模块的个数
        let res = await proxy!.$insideHttp.get("/socket/getModuleNum")
        module_num.value = res.data.data.moduleNum
        params.uv = res.data.data.uv - 0 // 获取紫外的速率参数
        params.inf = res.data.data.inf - 0 //获取红外的速率参数
        params.other = res.data.data.other - 0 // 获取温度、湿度、压力的速率参数

        //@ts-ignore
        for(let i=1;i<=module_num.value;i++) {
          if (i == 1) {
              //@ts-ignore
              module_list.value.push({
                id: 1,
                deviceName: "监测点1",
                isChecked: true
              })
          } else {
              //@ts-ignore
            module_list.value.push({
                id: i,
                deviceName: "监测点"+i,
                isChecked: false
              })
          }
        }
        module_store.initModuleList()
      }
    }

  // 重置视图
  const resetView = async (argId?:number | undefined) => {
    if (typeof argId === 'undefined') {
      uvcPirture && uvcPirture.resize()
      infPirture && infPirture.resize()
      temPirture && temPirture.resize()
      humPirture && humPirture.resize()
      prePirture && prePirture.resize()
      history_pie_pirture && history_pie_pirture.resize()
      history_bar_pirture && history_bar_pirture.resize()
    } else {
      switch (argId) {
        case 1: uvcPirture && uvcPirture.resize();break;
        case 2: infPirture && infPirture.resize();break;
        case 3: temPirture && temPirture.resize();break;
        case 4: humPirture && humPirture.resize();break;
        case 5: prePirture && prePirture.resize();break;
      }
    }
  }
  const resizeAll = () => { resetView() }
  const resizeOne = (id:number | undefined) => { if (!id) return; resetView(id) }
  // 关闭放大
  let closeZoom = () => {
    let panels = document.querySelectorAll(".chart")
    proxy.$nextTick(() => {
      let currentRef = orderList[zoomId.value - 1].refName
      coverShow.value = false
      const currentDom:HTMLElement = eval(`${currentRef}.value`)
      panels[zoomId.value - 1].appendChild(currentDom)
      currentDom.style.height = ""
      currentDom.style.width = ""
      resizeOne(zoomId.value)
      switch(zoomId.value) {
        case 1:{uvcArr = Tool.tool.initArrayLength(uvcArr);xaxisData = Tool.tool.initArrayLength(xaxisData,time.value);renderUvcPirture()};break;
        case 2:{infArr = Tool.tool.initArrayLength(infArr);xaxisData = Tool.tool.initArrayLength(xaxisData,time.value);renderInfPirture()};break;
        case 3:{temArr = Tool.tool.initArrayLength(temArr);xaxisData1 = Tool.tool.initArrayLength(xaxisData1,other_time.value);renderTemPirture()};break;
        case 4:{humArr = Tool.tool.initArrayLength(humArr);xaxisData1 = Tool.tool.initArrayLength(xaxisData1,other_time.value);renderHumPirture()};break;
        case 5:{preArr = Tool.tool.initArrayLength(preArr);xaxisData1 = Tool.tool.initArrayLength(xaxisData1,other_time.value);renderPrePirture()};break;
      }
      Tool.tool.len = 8
      zoomId.value = 0
    })
  }
  // 放大
  let zoom = (id:number|undefined) => {
      zoomId.value = id
      coverShow.value = true
      Tool.tool.len = 200
      let currentDevice:string | undefined = orderList[id- 1].refName // 获取设备的引用
      let currentDom:HTMLElement = eval(`${currentDevice}.value`) // 获取当前的设备元素
      currentDom.style.height = "100%"
      currentDom.style.width = "100%"
      proxy.$nextTick(() => {
          cover.value.appendChild(currentDom)
          resizeOne(id)
      })
  }
  // 放大的设备列表
  const orderList:Array<obj> = [
    {
      orderName: "message.uv",
      id: 1,
      refName: "uvcRef"
    },
    {
      orderName: "message.inf",
      id: 2,
      refName: "infRef"
    },
    {
      orderName: "message.tem",
      id: 3,
      refName: "temRef"
    },  {
      orderName: "message.hum",
      id: 4,
      refName: "humRef"
    },
    {
      orderName: "message.pre",
      id: 5,
      refName: "preRef"
    }
  ]

  const deviceSize = () => {
    if (document.body.clientWidth < 1400) {
      Tool.tool.len = 6
    } else if (document.body.clientWidth > 1500) {
      Tool.tool.len = 8
    }
  }

  const isRsize = ref(false)
  // 生命周期
  onMounted(async () => {
    let {data:res}:{data:IhttpReturn} = await proxy!.$insideHttp.get("/socket/addRunDate")
          if (res.code == 200) {
             // 需要重新请求数据
             deleteWorker.postMessage(true)
             console.log("添加日期，查看数据库是否超过七天")
          }
          //@ts-ignore
          indexDbNum.value = await indexDb.countNum("list")
          
          await getModuleNum()
          // 初始化websocket
          initWebsocket()
          // 初始化各个传感器的参数
          initEchart()

          deviceSize()

          render_production()

          render_history()

          render()

         resetView()

      // 点击切换报警信息查看
      history_pie_pirture.on("click", async (params:any) => {
        let name:string = params.data.name
        let color:string = params.data.select.itemStyle.shadowColor as string
        let my_params:string = ""
        switch(name) {
          case "紫外": my_params = "uvc_sta";break;
          case "红外": my_params = 'ir_sta';break;
          case "温度": my_params = "temp_sta";break;
          case "湿度": my_params = "hum_sta";break;
          case "压力": my_params = "pre_sta";break;
        }
        let { data:res } = await proxy.$adminHttp.get("/admin/getHistory",{
          params: {
            module_id: device_currentId.value,
            type: my_params
          }
        })
        render_history(`监测点${device_currentId.value}${name}`,color,res.data.dateList,res.data.errNum)
  })
         const onWinResize = () => {
           if (resizeTimer) clearTimeout(resizeTimer)
           resizeTimer = setTimeout(() => {
             requestAnimationFrame(() => {
               deviceSize()
               resizeAll()
             })
           }, 100)
         }
         window.addEventListener("resize", onWinResize)
         winResizeHandler = onWinResize
          // 判断程序是否在后台运行 => 优化项目
          window.addEventListener("visibilitychange",() => {
              if (document.hidden) {
                // 在后台运行项目
                isShowTip.value = false
              } else {
                // 在前台运行项目
                isShowTip.value = true
              }
          })
          resizeObserver = new ResizeObserver(entries => {
            entries.forEach(entry => {
              const el = entry.target as HTMLElement
              const chart = chartDomMap.get(el)
              if (chart) chart.resize()
            })
          })
          if (uvcRef.value) { chartDomMap.set(uvcRef.value as HTMLElement, uvcPirture); resizeObserver.observe(uvcRef.value as HTMLElement) }
          if (infRef.value) { chartDomMap.set(infRef.value as HTMLElement, infPirture); resizeObserver.observe(infRef.value as HTMLElement) }
          if (temRef.value) { chartDomMap.set(temRef.value as HTMLElement, temPirture); resizeObserver.observe(temRef.value as HTMLElement) }
          if (humRef.value) { chartDomMap.set(humRef.value as HTMLElement, humPirture); resizeObserver.observe(humRef.value as HTMLElement) }
          if (preRef.value) { chartDomMap.set(preRef.value as HTMLElement, prePirture); resizeObserver.observe(preRef.value as HTMLElement) }
          if (history_pie.value) { chartDomMap.set(history_pie.value as HTMLElement, history_pie_pirture); resizeObserver.observe(history_pie.value as HTMLElement) }
          if (history_bar.value) { chartDomMap.set(history_bar.value as HTMLElement, history_bar_pirture); resizeObserver.observe(history_bar.value as HTMLElement) }
})
  const initEchart = () => {
      uvcPirture = echarts.init(uvcRef.value)
      infPirture = echarts.init(infRef.value)
      temPirture = echarts.init(temRef.value)
      prePirture = echarts.init(preRef.value)
      humPirture = echarts.init(humRef.value)
        // 历史数据统计
      history_pie_pirture = echarts.init(history_pie.value)
      history_bar_pirture = echarts.init(history_bar.value)
    }
    // 统计设备的报警状态
    let totalStatus = {
       error: {
        idList: [new Set([]),new Set([]),new Set([]),new Set([]),new Set([])],
        errorCount: 0,
        info: [],
       },
       statuList: [
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map(),
         new Map()
       ]
    }

    // 语言播报
    const handleSpeak = (text:string):void => {
        msg.text = text // 文字内容: 测试内容
        msg.lang = "zh-CN"; // 使用的语言:中文
        msg.volume = 1; // 声音音量：1
        msg.rate = 1.4; // 语速：1
        msg.pitch = 1; // 音高：1
        synth.speak(msg); // 播放
    }
    const synth = window.speechSynthesis
    const msg = new SpeechSynthesisUtterance()

    // 本地报警存储
    import indexDb from '../local/indexDb'
    let countNum = ref(0)
    onUnmounted(() => {
      if (winResizeHandler) window.removeEventListener('resize', winResizeHandler)
      if (resizeObserver) resizeObserver.disconnect()
    })
    const countNormal = async (obj:any,id:number,valueList: Array<any>) => {
      for(let i=0;i<5;i++) {
        if (obj[i] !== 0) {
          // @ts-ignore
          totalStatus.error.idList[i].add(id)
          totalStatus.error.errorCount++

          // 判断报警状态是否一直都没变
        if (!(deviceStatusList.value[id - 1].has(i) && deviceStatusList.value[id - 1].get(i) == obj[i])) {
                deviceStatusList.value[id - 1].set(i,obj[i])
                saveErrorInfoWorker.postMessage({
                    level: obj[i],
                    data: valueList[i],
                    module_id: id,
                    type: i,
                    info: `${proxy.$t("message.point")}${id}${proxy?.$t(orderList[i].orderName)}${proxy.$t("message.occurred")}${valueList[i]}`
                })
                indexDbNum.value +=1
                await indexDb.addData("list", {
                   date: new Date().toLocaleString(),
                   info: `${proxy.$t("message.point")}${id}${proxy?.$t(orderList[i].orderName)}${proxy.$t("message.occurred")}${valueList[i]}`
                })
             }
         // 是否可以发送短信
         if (admin_store.isAableSendMsg) {
            // 发送短信进行提醒用户
            //@ts-ignore
            sendWorker.postMessage(JSON.stringify({
                // @ts-ignore
                phoneList: admin_store.phoneList.filter(item => item.isWatch),
                module_id: id,
                type: i,
                value: valueList[i]
            }))
         }
        } else {
          deviceStatusList.value[id - 1].set(i,0)
        }
      }
       countNum.value ++
      if (countNum.value == 5) {
        countNum.value = 0
        if (totalStatus.error.errorCount > 0) {
          // isShowTip 控制前台还是后台省的占用空间
          if (isShowTip.value) {
                  totalStatus.error.idList.forEach((item,index) => {
                      if (item.size>0) {
                        //@ts-ignore
                        totalStatus.error.info.push(`${proxy?.$t("message.point")}${Array.from(item).sort((a,b) => a-b).join('，')}，${proxy?.$t(deviceNameList.value[index])}`)
                      }
              })
            if (isOpenVoice.value){handleSpeak(`${totalStatus.error.info.join("，")}，${proxy.$t("message.catch")}`)} else {synth.cancel(msg)}
            // 控制用户是否使用弹框提醒
              if (alarm_type.value !== 2) {
                  proxy.$message({
                      message: `${totalStatus.error.info.join("，")}${proxy.$t("message.catch")}`,
                      type: 'error',
                      duration: 1200
                    })
                    alarm_type.value = 1
                  }
              }
        } else {
             synth.cancel(msg)
             alarm_type.value = 0
        }

           // 重新清空统计
          totalStatus.error.info = []
          totalStatus.error.errorCount = 0
          totalStatus.error.idList = [new Set([]),new Set([]),new Set([]),new Set([]),new Set([])]
        }
      }
    // 切换设备
   const taggleDevice = (id:number) => {
	      device_currentId.value = id
        time.value = 0
        inf_time.value = 0
        infArr = []
        uvcArr = []
        preArr = []
        humArr = []
        temArr = []
        other_time.value = 0
        xaxisData1 = []
        xaxisData = []
        xaxisData2 = []
        module_list.value.forEach(item => item.isChecked = false)
        module_list.value[id - 1].isChecked = true
        proxy.notifySuccess("切换到"+ module_list.value[id-1].deviceName)
    }
    let xaxisData1 = reactive<Array<number>>([])
    let other_time = ref(0)
    // 发送给手机
    let sendAppMsg = function(device_data:Array<number>) {
      if (store.deviceList.length >= 2) {
        console.log(store.websocket)
                  // @ts-ignore
                  store.websocket.send(
                      JSON.stringify({
                      action: "sendData",
                      token:store.userInfo.token,
                      linkCode: store.linkCode,
                      data: Object.assign({runTime: new Date().getTime(),speed: store.speed,module_num: module_num.value},device_data)
                    }))
                }
        }
        let inf_time = ref(0) // 红外的x轴
        let xaxisData2 = reactive<Array<number>>([])
        let renderInfTime = ref<number>(new Date().getTime()) // 获取红外时间戳
        let renderOtherTime = ref<number>(new Date().getTime()) // 获取温湿压时间戳
        let renderUvTime = ref<number>(new Date().getTime()) // 获取紫外时间戳
        //导入报警信息存储线程
        import saveErrorMsg from '@/worker/saveErrorMessage?worker' // 保存报警信息
        let saveErrorInfoWorker = new saveErrorMsg()

    /**渲染部分 */
    const render = async () => {
      try {
        // @ts-ignore
        localWebsocket.value.onmessage = async (msg) => {
          let device_data = JSON.parse(msg.data)

          if (device_data.action === 'sendData') {
              // 发送给手机
              sendAppMsg(device_data)

            // 自动切换监测点
            // isToggleDevice(device_data.sta[5])
            if (device_currentId.value == device_data.ID) {
            let uvc_val = device_data.data[0]// 紫外的数值
            let inf_val = device_data.data[1] // 红外的数值
            let tem_val = device_data.data[2] // 温度的数值
            let hum_val = device_data.data[3] // 湿度的数值
            let pre_val = device_data.data[4] // 压力的数值
            if (!zoomId.value) {
              let currentTime:number = new Date().getTime()
              let isRender:boolean = (currentTime - renderOtherTime.value) > rateLevel.value[params.other - 1] // 是否可以渲染温度湿度压力等
              let isInfRender:boolean = (currentTime - renderInfTime.value) > rateLevel.value[params.inf - 1] // 是否可以渲染红外等
              let isUvRender:boolean = (currentTime - renderUvTime.value) > rateLevel.value[params.uv - 1]

              // 渲染其他参数
              if (isRender) {
                renderOtherTime.value = new Date().getTime()
                other_time.value ++
                xaxisData1 = Tool.tool.limitArrayLength(xaxisData1,other_time.value)
              }
              // 渲染红外
              if (isInfRender && inf_val !== ' ') {
                renderInfTime.value = new Date().getTime()
                inf_time.value ++
                xaxisData2 = Tool.tool.limitArrayLength(xaxisData2,inf_time.value)
                infArr = Tool.tool.limitArrayLength(infArr,inf_val)
                renderInfPirture()
              }
              // 渲染紫外
              if (isUvRender && uvc_val !== ' ') {
                renderUvTime.value = new Date().getTime()
                 time.value ++
                 xaxisData = Tool.tool.limitArrayLength(xaxisData,time.value)
                 uvcArr = Tool.tool.limitArrayLength(uvcArr,uvc_val)
                 renderUvcPirture()
              }
                if (pre_val !== ' ' && isRender) preArr = Tool.tool.limitArrayLength(preArr,pre_val)
                if (hum_val !== ' ' && isRender) humArr = Tool.tool.limitArrayLength(humArr,hum_val)
                if (tem_val !== ' ' && isRender) temArr = Tool.tool.limitArrayLength(temArr,tem_val)

                if (pre_val !== ' ' && isRender) renderPrePirture()
                if (hum_val !== ' ' && isRender) renderHumPirture()
                if (tem_val !== ' ' && isRender) renderTemPirture()

            } else {
            let currentTime:number = new Date().getTime()
              let isRender:boolean = (currentTime - renderOtherTime.value) > rateLevel.value[params.other - 1] // 是否可以渲染温度湿度压力等
              let isRenderUv:boolean = (currentTime - renderUvTime.value) > rateLevel.value[params.uv - 1]
              let isRenderInf:boolean = (currentTime - renderInfTime.value) > rateLevel.value[params.inf - 1]
              if (isRender) renderOtherTime.value = new Date().getTime()
              if (isRenderInf) renderInfTime.value = new Date().getTime()
              if (isRenderUv) renderUvTime.value = new Date().getTime()
            switch(zoomId.value) {
              case 1: {
                // 添加数组
                if (uvc_val !== ' ' && isRenderUv) {
                  time.value ++
                  xaxisData = Tool.tool.limitArrayLength(xaxisData,time.value)
                  uvcArr = Tool.tool.limitArrayLength(uvcArr,uvc_val);
                  renderUvcPirture()
                }
              };break;
              case 2: {
                if (inf_val !== ' ' && isRenderInf) {
                    inf_time.value ++
                    xaxisData2 = Tool.tool.limitArrayLength(xaxisData2,inf_time.value)
                    infArr = Tool.tool.limitArrayLength(infArr,inf_val)
                    renderInfPirture()
                }
              };break;
              case 3: {
                if (tem_val !== ' ' && isRender) {
                  other_time.value ++
                  temArr = Tool.tool.limitArrayLength(temArr,tem_val)
                  xaxisData1 = Tool.tool.limitArrayLength(xaxisData1,other_time.value)
                  renderTemPirture()
                }
            };break;
            case 4: {
              if (hum_val !== ' ' && isRender) {
                other_time.value ++
                xaxisData1 = Tool.tool.limitArrayLength(xaxisData1,other_time.value)
                  humArr = Tool.tool.limitArrayLength(humArr,hum_val)
                  renderHumPirture()
                }
            };break;
            case 5: {
            if (pre_val !== ' ' && isRender) {
                  other_time.value ++
                  preArr = Tool.tool.limitArrayLength(preArr,pre_val)
                  xaxisData1 = Tool.tool.limitArrayLength(xaxisData1,other_time.value)
                  renderPrePirture()
                }
              };break;
            }
            }
            }
            let statusList = device_data.sta
            countNormal(statusList,device_data.ID,device_data.data)
            } else if(device_data.action === "renderSystemInfo") {
                systemInfo.value = device_data
             } else if(device_data.action === "get_val") {
                store.setting = device_data.data
             }
            }
        } catch(err) {
            console.log(err)
        }
    }
      // 渲染红外
      const renderInfPirture = () => {
      // 获取红外的量程
      infMin.value = Tool.tool.getMinValue(infArr)
      infMax.value = Tool.tool.getMaxValue(infArr)
      infPirture.setOption(setOption(proxy.$t("message.point") + device_currentId.value + proxy?.$t("message.inf") + ' ' +"/℃","#34d1fd",xaxisData2,infArr,infMin.value,infMax.value,proxy.$t("message.time"),proxy?.$t("message.value")))
    }
    // 渲染紫外
    const renderUvcPirture = () => {
       //紫外的量程
       uvcMax.value = Tool.tool.maxArr(uvcArr) + 400
       uvcMin.value = Math.round(Tool.tool.minArr(uvcArr) - 400)
       uvcPirture.setOption(setOption(proxy.$t("message.point") + device_currentId.value + proxy?.$t("message.uv"),"#ffaaff",xaxisData,uvcArr, uvcMin.value,uvcMax.value,proxy.$t("message.time"),proxy?.$t("message.value")));
    }
    // 渲染温度
    const renderTemPirture = () => {
      // 获取温度的量程
      temMin.value = Tool.tool.getMinValue(temArr)
      temMax.value = Tool.tool.getMaxValue(temArr)
      temPirture.setOption(setOption(proxy.$t("message.point") + device_currentId.value + proxy?.$t("message.tem")+"/℃","#c30720",xaxisData1,temArr,temMin.value,temMax.value,proxy.$t("message.time"),proxy?.$t("message.value")));
    }

    // 渲染湿度
    const renderHumPirture = () => {
      // 获取湿度的量程
      humMax.value = Tool.tool.getMaxValue(humArr)
      humMin.value = Tool.tool.getMinValue(humArr)
      humPirture.setOption(setOption(proxy.$t("message.point") + device_currentId.value + proxy?.$t("message.hum") +"/%RH","#00ffa2",xaxisData1,humArr,humMin.value,humMax.value,proxy.$t("message.time"),proxy?.$t("message.value")));
    }
    // 渲染压力
    const renderPrePirture = () => {
      // 获取压力的量程
      preMax.value = Tool.tool.getMaxValue(preArr)
      preMin.value = Tool.tool.getMinValue(preArr)
      prePirture.setOption(setOption(proxy.$t("message.point") + device_currentId.value + proxy?.$t("message.pre") +"/Kpa","#ffba00",xaxisData1,preArr,preMin.value,preMax.value,proxy.$t("message.time"),proxy?.$t("message.value")));
    }

    // 建立websocket连接
    const initWebsocket = () => {
      // @ts-ignore
      localWebsocket.value = new WebSocket("ws://"+import.meta.env.VITE_APP_BASEURL_WEBSOCKET)
        // @ts-ignore
        localWebsocket.value.onopen = function() {
            console.log("本地连接已经打开")
            localWebsocket.value.send(JSON.stringify({action: 'get_val'}))
          }
          // @ts-ignore
          localWebsocket.value.onclose = function() {
            console.log("断开连接")
            setTimeout(() => {
              if (isLogin.value) {initWebsocket();render();}
            }, 500);
          }
    }
// 判断连接是否存在
setInterval(() => {
  //@ts-ignore
  if (localWebsocket.value && localWebsocket.value.readyState !== 3) return
  if (isLogin.value) {
    initWebsocket()
    render()
  }
},1000*30)

    /**历史统计 */
    import { historyTotal, historyNum } from '../until/chart'
    let history_pie = ref() // 模块分布
    let history_bar = ref() // 模块报警
    let history_pie_pirture = reactive<ECharts>({} as ECharts)
    let history_bar_pirture = reactive<ECharts>({} as ECharts)

    // 渲染产品分布
    const render_production = () => {
      history_pie_pirture.setOption(historyTotal())
    }
    // 报警统计
    const render_history = (title?:string,color?:string,x?:Array<string>,y?:Array<number>) => {
      history_bar_pirture.setOption(historyNum(title,color,x,y))
    }

</script>
<style scoped lang="less">

main {
  padding: 20px 10px;
  height: calc(100% - 80px);
}

.cover {
    height: calc(100% - 40PX);
    position: absolute;
    top: 40PX;
    left: 0;
    width: 100%;
    z-index: 999;
    background:#1d335d;
    display: flex;
    align-items: stretch;
    .chart-item {
      width: 100%;
      height: 100%;
    }
    .el-icon {
      position: absolute;
      z-index: 9999;
      top:0;
      right: 0;
    }
  }
.el-row {
  height: 100%;

  .left,.right {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}
.my_chart {
  flex: 1;
  display: flex;
  flex-direction: column;
}

  .chart {
    width: 100%;
    flex: 1;
    padding-left: 5px;
    border: 0.008rem solid rgba(14,253,255,0.5);
    position: relative;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    .chart-item {
       flex: 1;
       padding-bottom: 2px;

    }
    &:last-child {
      margin-bottom: 0px;
    }
    h3 {
      font-size: 20px;
      color: #fff;
      height: 50px;
      line-height: 50px;
      position: relative;
      .el-icon {
        position: absolute;
        top: 5px;
        right: 0;
      }
    }
    .border_bg_leftTop {
      position: absolute;
      left: -0.008rem;
      top: -0.04rem;
      width: 0.37rem;
      height: 0.05rem;
      display: block;
      background: #29292f url("../assets/images/title_left_bg.png") no-repeat;
      background-size: cover;
    }
  }
  .middle-header {

    .title {
      width: 100%;
      text-align: center;
      color: rgb(46, 192, 246);
      font-size: 30px;
      height: 70px;
      line-height: 70px;
    }
    .description {
      color: rgb(255, 255, 255);
      font-size: 20px;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
  }
   // 收益明细
   #income {
      ul {
        height: 100%;
        display: grid;
        grid-template-rows: repeat(2,1fr);
        grid-template-columns: repeat(3,1fr);
        list-style: none;
        gap: 5px 10px;
        li {
          div {
            font-size: 30px;
            color: rgba(14,253,255,1);
            font-family: dig;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: normal;
          }
          p {
            color: #fff;
            font-size: 16px;
            text-align: center;
          }
        }
      }
   }

.drawer-main {
  padding: 50px 0;
  width: 100%;
  height: 34%;
  .flex_layout {
      width: 100%;
      height: 100%;
      display: grid;
      grid-template-columns: repeat(3,1fr);
      .module_item {
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .img {
          background: url("../assets/contentBg.png") no-repeat center;
          border: 2px solid #d6d4d4;
          border-radius: 50%;
          width: 160px;
          height: 160px;
          box-shadow: 6px 2px 18px rgba(0,0,0,.7);
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          img {
            width: 50px;
            height: 50px;
          }
        }
        p {
          text-align: center;
          color: #fff;
        }
      }
    }
  .el-carousel {
      width: 100%;
      height: 100%;
      :deep(.el-carousel__container) {
        height: 100%!important;
      }
     :deep(.el-carousel__arrow) {
       transform: scale(1.1);
       background: rgba(186, 186, 186, 0.4);
      }
    }
    .grid_layout {
        width: 100%;
        height: 100%;
        display: grid;
        grid-template-columns: repeat(3,1fr);
      }

  .module_item {
    display: flex;
    justify-content: center;
    .module_bg_img {
      width: 160px;
      height: 160px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-image: url("../assets/contentBg.png");
      background-size: cover;
      background-position: center;
      border: 2px solid #d6d4d4;
      border-radius: 50%;
      box-shadow: 6px 2px 18px rgba(0,0,0,.7);
    .img {
      width: 120px;
      height: 120px;
      justify-content: center;
      align-items: center;
      display: flex;
      flex-direction: column;
      img {
        width: 50px;
        height: 50px;
      }
      p {
      width: 100%;
      text-align: center;
      color: #fff;
    }
    }
  }
  }
}
/**激活模块高亮 */
.activeModule {
  border: 10px solid #d6d4d4;
}

/**边框动画 */
@keyframes borderAnimation {
  0% {
    border: red;
    box-shadow: 0 0 0 rgba(249, 29, 0,.6);
  }
  60% {
    border: red;
    box-shadow: 0 0 3px rgba(249, 29, 0,.6);
  }
  100% {
    border: none;
  }
}

.system_info {
  height: 130px;
  position: relative;
  border: 0.008rem solid rgba(14,253,255,0.5);
  margin-bottom: 20px;
  h3 {
    color: #fff;
    font-size: 20px;
      color: #fff;
      height: 50px;
      line-height: 50px;
      padding-left: 5px;
  }
  .info_container {
    width: 100%;
    justify-content: space-around;
    height: calc(100% - 50px);
    display: flex;
    .info_item {
      width: 30%;
      display: flex;
      justify-content: center;
      align-items: center;
      p {
        text-align: center;
      }
      .left {
        display: flex;
        flex-direction: column;
        margin-right: 10px;
        justify-content: center;
        p {
          &:first-child {
            margin-bottom: 5px;
            span {
              display: inline-block;
              font-size: 28px;
            }
          }
          &:last-child {
            color: #fff;
            font-size: 16px;
          }
        }
      }
      .right {
        display: flex;
        align-items: center;
        justify-content: center;
        img {
          width: 90%;
          height: 60%;
        }
      }
    }
  }

  .border_bg_leftTop {
    position: absolute;
      left: -0.008rem;
      top: -0.04rem;
      width: 0.37rem;
      height: 0.05rem;
      display: block;
      background: #29292f url("../assets/images/title_left_bg.png") no-repeat;
      background-size: cover;
  }
}

.mainCenter {
    padding-bottom: 0;
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    flex-direction: column;
    border: 0.008rem solid rgba(14,253,255,0.5);
    .total {
      display: flex;
      width: 100%;
      padding: 0;
      height: 49%;
      justify-content: space-between;
      aside {
        &:first-child {
          width: 45%;
        }
        &:last-child {
          width: 52%;
        }
      }
    }
  }
</style>
